package com.ipay.wechat.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ipay.utils.StringUtil;
import com.ipay.wechat.dao.TPayresultDao;
import com.ipay.wechat.pojo.TPayresultEntity;
import com.ipay.wechat.pojo.WXTicket;
import com.ipay.wechat.service.TPayresultService;

import com.ipay.wechat.util.CustomException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ipay.redis.JedisExecutor;
import com.ipay.redis.JedisKeyPrefix;
import com.ipay.utils.Constant;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.dao.TradeRecordDao;
import com.ipay.wechat.pojo.AccessToken;
import com.ipay.wechat.pojo.TradeRecord;
import com.ipay.wechat.service.TradeRecordService;
import com.ipay.wechat.util.AccessTokenUtil;
import com.ipay.wechat.util.HttpUtils;
import com.ipay.wechat.util.PushMessage;

import org.springframework.transaction.annotation.Transactional;

@Service("trService")
public class TradeRecordServiceImpl implements TradeRecordService {
	private Logger logger=LoggerFactory.getLogger(getClass());
	@Autowired
	private JedisExecutor jedies;
	@Autowired
	private Wechat wechat;
	@Autowired
	private TradeRecordDao tradeRecordDao;
	@Autowired
	private TPayresultDao resultDao;

	@Override
	public List<TradeRecord> findTradeRecordList(Map<String, Object> map) {
		return tradeRecordDao.findTradeRecordList(map);
	}

    @Override
    public List<TradeRecord> findTkTradeRecordList(Map<String, Object> map) {
        return tradeRecordDao.findTkTradeRecordList(map);
    }

    @Override
	public TradeRecord findTradeRecordDetails(String recordNo) {
		// TODO Auto-generated method stub
		return tradeRecordDao.findTradeRecordDetails(recordNo);
	}
    @Override
	public TradeRecord queryByRecordNo(String recordNo) {
		// TODO Auto-generated method stub
		return tradeRecordDao.queryByRecordNo(recordNo);
	}

	@Override
	public List<String> findDateGrouping(TradeRecord payorder) {
		// TODO Auto-generated method stub
		return tradeRecordDao.findDateGrouping(payorder);
	}

	@Override
	public List<Map<String,String>> queryMerchantInfoList(TradeRecord payorder) { //扇形统计图数据查询 queryMerchantInfoList
		// TODO Auto-generated method stub
		return tradeRecordDao.queryMerchantInfoList(payorder);
	}
	@Override
	public List<Map<String,String>> queryCategoryAmount(TradeRecord payorder) { //扇形统计图数据查询 queryMerchantInfoList
		// TODO Auto-generated method stub
		return tradeRecordDao.queryCategoryAmount(payorder);
	}

	@Override
	public List<TradeRecord> findTradeRecordPage(TradeRecord payorder) {
		return tradeRecordDao.findTradeRecordPage(payorder);
	}
	@Override
	public BigDecimal findTodaySumAmount(Map<String, Object> map){
		return tradeRecordDao.findTodaySumAmount(map);
	}

	@Override
	public BigDecimal findRefundSumAmount(Map<String, Object> map) {
		return tradeRecordDao.findRefundSumAmount(map);
	}

	@Override
	public Integer findCountRecord(Map<String, Object> map){
		return tradeRecordDao.findCountRecord(map);
	}

	/**
	 * * 修改退款订单状态
	 * @param payorder
	 */
	@Override
	@Transactional
	public void updateRefundStart(TradeRecord payorder){
		logger.info("***************================================updateRefundStart==================================***************");
		tradeRecordDao.updateRefundStart(payorder);
		TradeRecord tradeRecord = tradeRecordDao.queryByRecordNo(payorder.getRecordNo());///查询退款订单信息
		if(tradeRecord!=null&&StringUtil.isNotEmpty(tradeRecord.getOrderId())) {
			TradeRecord payOrderFQ=new TradeRecord();
			payOrderFQ.setStatus(payorder.getStatus());
			payOrderFQ.setRemark(payorder.getRemark());
			payOrderFQ.setRefundTime(payorder.getRefundTime());
			payOrderFQ.setRecordNo(tradeRecord.getOrderId());
			int nub = tradeRecordDao.updateOrder(payOrderFQ);//修改退款订单对应的订单状态
			logger.info("====:"+nub+"***************=============updateRefundStart======***************OrderId:"+tradeRecord.getOrderId()+"   RecordNo:"+payorder.getRecordNo());
		}else{
			try {
				throw new CustomException("无法查询到退款订单对应的订单信息(发起支付订单信息)"); // 异常信息
			} catch (CustomException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * * 支付通知结果  存表
	 * 修改订单状态
	 * @param payorder
	 * @param entity
	 */
    @Override
	@Transactional
    public void updateRefundStart(TradeRecord payorder,TPayresultEntity entity) {
    	if(StringUtil.isNotEmpty(entity.getOutTradeNo())){
			resultDao.save(entity);
		}
		tradeRecordDao.updateRefundStart(payorder);
    }

	/**
	 * //修改退款订单对应的订单状态
	 * @param payorder
	 */
	@Override
	public void updateOrder(TradeRecord payorder) {
		tradeRecordDao.updateOrder(payorder);
	}

	@Override
	public void save(TradeRecord payorder) {
		// TODO Auto-generated method stub
		tradeRecordDao.save(payorder);
	}
	
	
	
	@Override
	public void pushTradeMessage(Map<String, Object> map) {
		String access_token = getAccessToken();

		String sendType = String.valueOf(map.get("sendType"));
		HashMap<String, String> msgMap = new HashMap<String, String>();
		msgMap.put("index", "1");// index为1时 代表模版 不传url链接地址 ，index 为2时  msgMap传入一个url参数 模版的跳转地址
		msgMap.put("openid", String.valueOf(map.get("openid")));
		msgMap.put("sendType", sendType);
		msgMap.put("url", String.valueOf(map.get("url")));
		
		String result;
		String message = "";
		
		//msgMap.put("openid", "oejR50lPUQq5eRVL31sSIyEo0Ybg");
		//msgMap.put("url", "https://www.baidu.com/");
		
		if(sendType.equals("2")){//2 表示 收款成功通知
			msgMap.put("first", "您成功收到一笔付款\n");
			msgMap.put("tempCode", wechat.getTEMPLATE2());//消息模版编号 从配置文件中获取
			//msgMap.put("tempCode", "Ty_Ulkj5P2SlIKyrkyT0AtZwGAboX7jh_vceoDwjhwc");
			
			/*msgMap.put("keyword1", "1000.01元");//付款金额
			msgMap.put("keyword2", "腾讯");//商户名称
			msgMap.put("keyword3", "微信");//支付方式 微信 支付宝
			msgMap.put("keyword4", "56465138979461");//交易单号
			msgMap.put("keyword5", "2017-09-18 10:56:06");*/
			
			String keyword3 = String.valueOf(map.get("keyword3"));
			if(keyword3.equals(Constant.Resource.RESOURCE_WX.getValue())){
				msgMap.put("keyword3", "微信");//支付方式 微信 支付宝
			}else if(keyword3.equals(Constant.Resource.RESOURCE_ZFB.getValue())){
				msgMap.put("keyword3", "支付宝");
			}
			
			msgMap.put("keyword1", String.valueOf(map.get("keyword1") + "元"));//付款金额
			msgMap.put("keyword2", String.valueOf(map.get("keyword2")));//商户名称
			msgMap.put("keyword4", String.valueOf(map.get("keyword4")));//交易单号
			msgMap.put("keyword5", String.valueOf(map.get("keyword5")));//交易时间 格式 2016-12-12 10:08:08
		
			msgMap.put("remark", "感谢您的支持！点击查看更多信息");
			message = PushMessage.createMsgJson(msgMap);
			
		}else if(sendType.equals("3")){//3 表示  发送退款通知
			msgMap.put("tempCode", wechat.getTEMPLATE3());//消息模版编号 从配置文件中获取
			msgMap.put("first", "您成功收到一笔退款\n");
			msgMap.put("keyword1", "壕无理由，有钱任性");
			//msgMap.put("reason", String.valueOf(map.get("退款原因")));
			msgMap.put("keyword2", String.valueOf(map.get("keyword1") + "元"));
			msgMap.put("remark", "感谢您的支持！点击查看更多信息");
			message = PushMessage.createMsgJson(msgMap);
		}
		
		logger.info("message模版================"+message);
		result = HttpUtils.requestHttp("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token, "post", message);
		logger.info("调用结果-----------------"+result);
		JSONObject jsonObj = new JSONObject(result);
		int errCode = (int) jsonObj.get("errcode");
		if(errCode == 0){
			logger.info("调用成功");
		}
	}

    /**
     * 加载access_token到redis里
     * 加载jsapi_ticket到redis里
	 * http://blog.csdn.net/frankcheng5143/article/details/50163615
     */
    @Override
    public String freshAccessToken() {
        AccessToken accessToken = AccessTokenUtil.freshAccessToken(wechat);
        String asToken = accessToken.getAccess_token();
		WXTicket ticket = AccessTokenUtil.freshTicket(asToken);
		logger.info("====================asToken:"+asToken+"   ticket:"+ticket.getTicket());
        jedies.setValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WECHAT_TOKEN, "access_token", asToken, 6000);
        jedies.setValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_JSAPI_TICKET, "jsapi_ticket", ticket.getTicket(), 6000);
        return asToken;
    }

	/**
     * 获取redis里的access_token
     */
    @Override
    public String getAccessToken() {
        String access_token = jedies.getValue(JedisKeyPrefix.JEDIS_KEY_PREFIX_WECHAT_TOKEN, "access_token");
        while (StringUtil.isEmpty(access_token)) {
            access_token =freshAccessToken();;
        }
        return access_token;
    }

	@Override
	public TradeRecord queryByParam(Map<String, String> map) {
		return tradeRecordDao.queryByParam(map);
	}
}
